# -*- coding: utf-8 -*-
from django.db import models
from django.contrib.auth.models import User
from django.template import Context, loader

class Entity(models.Model):
    user = models.ForeignKey(User, related_name='entities')
    date = models.DateTimeField(auto_now=True)
    def __unicode__(self):
        try:
            return self.url.__unicode__()
        except:
            return self.blogentry.__unicode__()
    def rating(self):
        return self.opinions.aggregate(models.Sum('rating'))['rating__sum']
    def render(self):
        try:
            return self.url.render()
        except:
            return self.blogentry.render()
    class Meta:
        ordering = ["-date"]

class Url(Entity):
    address = models.URLField(verify_exists = False)
    def __unicode__(self):
        return self.address
    def render(self):
        t = loader.get_template('one_url.html')
        c = Context({'url': self,})
        return t.render(c)

class BlogEntry(Entity):
    subject = models.CharField(max_length = 128)
    text = models.TextField()
    def __unicode__(self):
        return self.subject
    def render(self):
        t = loader.get_template('one_entry.html')
        c = Context({'entry': self,})
        return t.render(c)

class Opinion(models.Model):
    RATING_CHOICES = ( (1, '+1'), (0, '0'), (-1, '-1'), )
    date = models.DateTimeField(auto_now=True)
    user = models.ForeignKey(User, related_name='opinions')
    entity = models.ForeignKey(Entity, related_name='opinions')
    rating = models.IntegerField(choices=RATING_CHOICES)
    comment = models.TextField()
    def render(self):
        t = loader.get_template('one_opinion.html')
        c = Context({'opinion': self})
        return t.render(c)

#class Similarity(models.Model):
#    pass

class Relationship(models.Model):
    rfrom = models.ForeignKey(User, related_name='friends')
    rto = models.ForeignKey(User, related_name='friend_of')

#class Tag(models.Model):
#    pass

#class Tagging(models.Model):
#    pass
